package com.bestv.search.common.dao.hibernate;

import com.bestv.search.common.dao.SearchConfigDao;
import com.bestv.search.common.model.SearchFieldInfo;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.sql.SQLException;
import java.util.List;

public class SearchConfigDaoHibernate extends GenericDaoHibernate<SearchFieldInfo, Long> implements SearchConfigDao {

    public SearchConfigDaoHibernate() {
        super(SearchFieldInfo.class);
    }

    @Override
    public int getSearchFieldInfosCount() {
        return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery("select count(id) from SearchFieldInfo ");
                String count = q.uniqueResult().toString();
                return Integer.parseInt(count);
            }
        });
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<SearchFieldInfo> getSearchFieldInfoPaging(final int start, final int limit) {
        return (List<SearchFieldInfo>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery("from SearchFieldInfo");
                q.setFirstResult(start);
                q.setMaxResults(limit);
                return q.list();
            }

        });
    }

    @SuppressWarnings("unchecked")
    @Override
    public SearchFieldInfo getSearchInfoByName(String name) {
        List<SearchFieldInfo> list = getHibernateTemplate().find("from SearchFieldInfo sfi where sfi.name=?", name);
        if (list == null || list.size() <= 0)
            return null;
        return list.get(0);
    }
}
